import axios from 'axios'
import Vue from 'vue'
import router from '../router'

axios.defaults.withCredentials = true //跨域写入cookie的配置

const instance = axios.create({
    baseURL:'/api',

})


//添加请求拦截器
instance.interceptors.request.use(function(config){
    //在发送之前可以判断当前用户状态
    //可以添加请求头等
    console.log('请求拦截')
    let userInfo = JSON.parse(localStorage.getItem('data'))
    if(userInfo === null){
        userInfo = {authToken:''}
    }

    // console.log(authToken)

    if(userInfo.authToken){
        config.headers.token = userInfo.authToken
    }

    return config

    }, function(error){
        return Promise.reject(error);
    });

//添加响应拦截器
instance.interceptors.response.use(function(response){
    //对响应数据的操作
    console.log('响应拦截')
    // console.log(response)
    let message = response.data.msg
    if(response.data.res){
        Vue.prototype.$message({
            message,
            type:"success"
          })
    }
    if(response.data.res === false){
        Vue.prototype.$message({
            message,
            type:"error"
          })
    }
    return response
},function(error){
    return Promise.reject(error)
})


export default instance